package com.thank.concurrency.samples.tests;

/**
 * description: none
 *
 * @author xiefayang
 * 2018/7/13 14:39
 */
public class SynchronizedDemo {

    public static synchronized void staticMethod() throws InterruptedException {
        System.out.println("静态同步方法开始");
        Thread.sleep(1000);
        System.out.println("静态同步方法结束");
    }

    public synchronized void method1() throws InterruptedException {
        System.out.println("实例同步方法1开始");
        Thread.sleep(1000);
        System.out.println("实例同步方法1结束");
    }

    public synchronized void method2() throws InterruptedException {
        System.out.println("实例同步方法2开始");
        Thread.sleep(3000);
        System.out.println("实例同步方法2结束");
    }


    public void method3() {
        System.out.println("同步代码块开始");
        int i = 0;
        synchronized (this) {
            i += 1;
        }

        System.out.println(i);
        System.out.println("同步代码块结束");
    }


    public static void main(String[] args) {

        SynchronizedDemo demo = new SynchronizedDemo();
        Thread thread1 = new Thread(() -> {
            try {
                demo.method1();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                demo.method2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread thread3 = new Thread(demo::method3);

        thread1.start();
        thread2.start();
    }
}
